#!/bin/sh /etc/rc.common
# Copyright (C) 2009 OpenWrt.org

START=02
USE_PROCD=1

add_enctype() {
	append enctypes $1	
}

add_ldap() {
        append ldap $1
}

add_kdc() {
	add_line "\t\tkdc                    = $1"
}

add_kadmind() {
	add_line "\t\tkadmind                = $1"
}

add_line() {
	echo >>/etc/krb5.conf -e $1
}

add_realm() {
	enctypes=""
	ldap=""
	config_get name             $1 name        "LOCAL.NET"
	config_get max_live         $1 max_live    "16h"
	config_get max_renew        $1 max_renew   "7d"
	config_get master_key_type  $1 master_key_type "aes256-cts-hmac-sha1-96"
	config_list_foreach "$1" "enctype" add_enctype
	config_list_foreach "$1" "ldap" add_ldap
	domain=`echo $name | tr '[A-Z]' '[a-z]'`
	[ -z "$enctypes" ] && enctypes="aes256-cts-hmac-sha1-96:normal rc4-hmac:normal"

	[ "$first_realm" -eq "1" ] && {
		first_realm=0
		add_line "[libdefaults]"
		add_line "\tdefault_realm = $name"
		add_line
		add_line "[realms]" 
	}
	add_line "\t$name = {"
	add_line "\t\tdefault_domain         = $domain"
	add_line "\t\tmaster_key_type        = $master_key_type"
	add_line "\t\tkdc_supported_enctypes = $enctypes"
	add_line "\t\tsupported_enctypes     = $enctypes"
	config_list_foreach "$1" "kdc"     add_kdc
	config_list_foreach "$1" "kadmind" add_kadmind
	[ ! -z "$ldap" ] && add_line "\t\tdatabase_module        = openldap_$name"
	add_line "\t}"
	add_line
}

add_db() {
	config_get name             $1 name        "LOCAL.NET"
	config_get dn               $1 dn          "dc=local,dc=net"
	ldap=""
	config_list_foreach "$1" "ldap" add_ldap
	[ ! -z "$ldap"  ] && {
		[ "$first_realm" -eq "1" ] && {
			first_realm=0
			add_line "[dbmodules]"
		}
		add_line "\topenldap_$name = {"
		add_line "\t\tdb_library                 = kldap"
		add_line "\t\tldap_servers               = $ldap"
#		add_line "\t\tldap_conns_per_server      = 5"
		add_line "\t}"
		add_line
	}
}

reload_service() {
	restart_service
}

service_triggers() {
	procd_add_reload_trigger "krb5"
}

start_service() {
	mkdir -p /var/etc
	echo -n >/etc/krb5.conf

	config_load krb5
	first_realm=1
	config_foreach add_realm realm
	first_realm=1
	config_foreach add_db realm
}
